<template>
  <el-dialog v-model="isDialogShow" :title="title" width="560" @closed="handleDialogClosed" @open="handleDialogOpen">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name"/>
      </el-form-item>
      <el-form-item label="配菜" prop="mealdesc">
        <el-input v-model="form.mealdesc"/>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="form.price" type="number"/>
      </el-form-item>
      <el-form-item label="口味" prop="taste">
        <el-input v-model.number="form.taste"/>
      </el-form-item>
      <el-form-item label="图片" prop="picture">
        <meal-picture-uploader v-model="form.picture"/>
      </el-form-item>
      <el-form-item label="出餐中心" prop="shopid">
        <meal-center-selector v-model="form.shopid" placeholder="请选择出餐中心"/>
      </el-form-item>
      <el-form-item label="餐品序号" prop="seq">
        <el-input-number :min="0" v-model="form.seq"/>
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input-number v-model="form.stock"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="2"/>
      </el-form-item>
      <!-- <el-form-item label="折扣" prop="discount">
        <el-input v-model.number="form.discount" type="number"/>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="handleConfirmClick">确定</el-button>
        <el-button @click="handleCancelClick">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import {computed, ref} from "vue"
import {ElForm, ElMessage} from "element-plus";
import {isAxiosError} from "axios";
import {MealRequest, MealType} from "@/api/types/meal";
import {addMeal, getMealById, updateMeal} from "@/api/meal";
import MealCenterSelector from "@/components/selector/MealCenterSelector.vue";
import MealPictureUploader from "@/components/uploader/MealPictureUploader.vue";

const props = defineProps<{ id?: number }>()
const emit = defineEmits<{
  addSuccess: []
  success: [mealCenterId: number, mealType: MealType]
  updateSuccess: []
}>()

const isDialogShow = defineModel<boolean>()

const title = computed(() => props.id === undefined ? "添加套餐" : "修改套餐")
const form = ref<MealRequest>({
  mealtype: "午餐",
  stock: 1,
  seq:1
})
const formRef = ref<InstanceType<typeof ElForm>>()
const rules = {
  // discount: [
  //   {
  //     type: "number",
  //     asyncValidator(rule: unknown, value: any): Promise<void> {
  //       return new Promise((resolve, reject) => {
  //         if (value === undefined || isNaN(value)) {
  //           reject("折扣不能为空")
  //         } else if (value < 0) {
  //           reject("折扣必须大于或等于0")
  //         } else if (value > 10) {
  //           reject("折扣必须小于或等于10")
  //         } else {
  //           resolve();
  //         }
  //       });
  //     },
  //   }
  // ],
  mealdesc: [
    {
      required: true,
      message: "配菜不能为空",
      trigger: "blur"
    }
  ],
  name: [
    {
      required: true,
      message: "名称不能为空",
      trigger: "blur"
    }
  ],
  picture: [
    {
      required: true,
      message: "图片不能为空",
      trigger: "change"
    }
  ],
  price: [
    {
      required: true,
      message: "价格不能为空",
      trigger: "blur"
    }
  ],
  status: [
    {
      required: true,
      message: "状态不能为空",
      trigger: "change"
    }
  ],
  shopid: [
    {
      required: true,
      message: "出餐中心不能为空",
      trigger: "change"
    }
  ],
  seq:[{
    required: true,
      message: "餐品序号不能为空",
      trigger: "blur"
  }],
  stock: [
    {
      required: true,
      message: "库存不能为空",
      trigger: "blur"
    }
  ],
  taste: [
    {
      required: true,
      message: "口味不能为空",
      trigger: "blur"
    }
  ],
}

const shortcutsForDatePicker = [
  {
    text: "今天",
    value: new Date(),
  },
]

async function getData() {
  if (props.id !== undefined) {
    const {result} = await getMealById(props.id)
    if (result !== undefined) {
      form.value = {
        id: result[0].id,
        name: result[0].name,
        price: result[0].price,
        taste: result[0].taste,
        picture: result[0].picture,
        mealdesc: result[0].mealdesc,
        mealtype: result[0].mealtype,
        shopid: Number(result[0].shopid),
       // discount: result[0].discount,
        status: result[0].status === 1 || result[0].status === 2 ? result[0].status : undefined,
        stock: result[0].stock,
        seq:result[0].seq
      }
    }
  }
}

function handleCancelClick() {
  isDialogShow.value = false
}

async function handleConfirmClick() {
  formRef.value?.validate(async (isValid: boolean) => {
    if (isValid) {
      try {
        if (props.id === undefined) {
          const {code, msg} = await addMeal(form.value)
          if (code === "200") {
            ElMessage.success(msg);
            emit("addSuccess")
            if (form.value.shopid !== undefined && form.value.mealtype !== undefined) {
              emit("success", form.value.shopid, form.value.mealtype)
            }
          } else {
            ElMessage.error(msg)
          }
        } else {
          const {code, msg} = await updateMeal(form.value)
          if (code === "200") {
            ElMessage.success(msg);
            emit("updateSuccess")
            if (form.value.shopid !== undefined && form.value.mealtype !== undefined) {
              emit("success", form.value.shopid, form.value.mealtype)
            }
          } else {
            ElMessage.error(msg)
          }
        }
        isDialogShow.value = false;
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  })
}

async function handleDialogClosed() {
  formRef.value?.resetFields()
}

async function handleDialogOpen() {
  await getData()
}
</script>
